package com.baseproject.datasource.get.request.type;

import com.baseproject.datasource.get.procedure.DataProcedure;
import com.baseproject.datasource.get.response.BaseResponseHandler;
import com.baseproject.datasource.local.LocalDataSource;
import com.baseproject.json.JsonUtils;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.Observable;

/**
 * Created by hp on 2017/8/18.
 */

public class ListRequestType extends RequestType {


    @Override
    public <T> void save(List<T> contentList, DataProcedure dataProcedure) {
        Class<T> className = dataProcedure.getClassName();
        Map<String, String> where = dataProcedure.getWhere();
        LocalDataSource.getInstance().updateItems(contentList, where);
    }

    @Override
    public <T> List<T> getListFromRemoteResponseData(Object objectData, Class<T> className) {
        jsonArrayData = BaseResponseHandler.createResponseHandler(objectData).getJSONArrayData();
        if (null != jsonArrayData) {
            List<T> contentList = new ArrayList<T>();
            for (int i = 0; i < jsonArrayData.length(); i++) {
                T t;
                try {
                    t = JsonUtils.getInstance().strToModel(jsonArrayData.get(i).toString(), className);
                } catch (JSONException e) {
                    throw new RuntimeException("JSONException!");
                }
                contentList.add(t);
            }
            return contentList;
        }
        return null;
    }

    @Override
    public <T> Observable<List<T>> getListFromLocal(DataProcedure dataProcedure, Class<T> className) {
        String[] projections = dataProcedure.getProjections();
        Map<String, String> where = dataProcedure.getWhere();
        return LocalDataSource.getInstance().getList(className, where, projections);
    }
}
